#coding:utf-8

import webapp2
import logging
import struct
import zlib
import base64
from webapp2_extras import sessions
from google.appengine.ext import ndb
from google.appengine.api import users

__password__ = ''
guestbook_key = ndb.Key('Guestbook', 'default_guestbook')

LoginHtml = """
<html><head>
<title>欢迎登录dagou</title>
</head>

<body>
<form name="loginForm" method="post" action="/sign">

<div id="login_bg">
    
        <center> 

    <div id="content_title">
        
        <h1>登录</h1>

    <div id="content">
           <div id="content_top"></div>
           <div class="login_main">
                       <table border="50" width="60%" align="center" cellpadding="2" cellspacing="2">
                <td width="60%">                                      
                <div class="login_box">                     
                      <div class="modify_oneline">
                        <div class="modify_text">帐号</div>
                        <input type="text" name="uid" size="20" tabindex="1" value="" class="inputBgLine modify_pw_input">
                      </div>
                      
                      <div class="modify_oneline">
                        <div class="modify_text">密码</div>
                        <input type="password" name="password" size="20" tabindex="2" value="" class="inputBgLine modify_pw_input">
                      </div>
                      
                      <div style="margin-left:20px;">
                        <div class="modify_oneline">
                          <div class="modify_text"></div>
                          <div><a class="underline" title="" href="/uniportal/modifyInfo.do?actionFlag=toGetPassword&amp;redirect=%2Funiportal%3Fredirect%3Dhttp%25253A%25252F%25252Fxinsheng.huawei.com%25252Fcn%25252F">忘记密码</a>
                                &nbsp;&nbsp;<a class="underline" title="" href="/uniportal/modifyInfo.do?actionFlag=toModifyPassword&amp;redirect=%2Funiportal%3Fredirect%3Dhttp%25253A%25252F%25252Fxinsheng.huawei.com%25252Fcn%25252F">修改密码</a>
                          </div>
                         </div>
                       </div>
                       
                       <input class="login_submit_pwd" type=submit tabindex="4" value="登录" onfocus="javascript:flagA=false;" onblur="javascript:flagA=true;">
        
                </div>
                </td>
                
                <td>
                <div class="login_welcome">
                    <h2>欢迎注册</h2>
                    <div class="gap32px"></div>
                    <p>您可以免费注册一个帐号，以获取更多的便利。</p>
                    <div class="gap16px"></div>&nbsp;
                    
                    <input name="regist" type="button" value="注册" onclick="window.open('/register')">
                </div>
                  </td>
                </table>
        
                <div class="clearBoth"></div>
           </div>
       <div id="content_bottom"></div>
    </div>
    </center>
</div>

</form>

</body>
</html>
"""
class Greeting(ndb.Model):
    author = ndb.UserProperty()
    content = ndb.TextProperty()
    date = ndb.DateTimeProperty(auto_now_add=True)

class BaseHandler(webapp2.RequestHandler):
    def dispatch(self):
        # Get a session store for this request.
        self.session_store = sessions.get_store(request=self.request)

        try:
            # Dispatch the request.
            webapp2.RequestHandler.dispatch(self)
        finally:
            # Save all sessions.
            self.session_store.save_sessions(self.response)

    @webapp2.cached_property
    def session(self):
        # Returns a session using the default cookie key.
        return self.session_store.get_session()
    
def handle_404(request, response, exception):
    logging.exception(exception)
    response.write('Oops! I could swear this page was here!')
    response.set_status(404)

def handle_500(request, response, exception):
    logging.exception(exception)
    response.write('A server error occurred!')
    response.set_status(500)

class UserHandler(BaseHandler):
    #response.headers.add(key,value)
    def get(self, user):
        test_value = self.session.get('test-value')
        if test_value:
            self.response.write('Session has this value: %r.' % test_value)
        else:
            self.session['test-value'] = 'Hello, session world!'
            self.response.write('Session is empty.')
    def post(self, user):
        pass

class Login(BaseHandler):
    def get(self):
        self.response.write(LoginHtml)
    def post(self):
        user = self.request.get("uid")
        ps = self.request.get("password")
        self.response.write("user %s login ps %s" %(user, ps))

class Upload(BaseHandler):
    def post(self):
        cookie = self.request.cookies.get('HTTP_COOKIE', '')
    
        # inflate = lambda x:zlib.decompress(x, -zlib.MAX_WBITS)
        wsgi_input = self.request.body
        if cookie:
            metadata = zlib.decompress(base64.b64decode(cookie), -zlib.MAX_WBITS)
        else:
            data = wsgi_input.read(2)
            metadata_length, = struct.unpack('!h', data)
            metadata = wsgi_input.read(metadata_length)
            metadata = zlib.decompress(metadata, -zlib.MAX_WBITS)
    
        headers = dict(x.split(':', 1) for x in metadata.splitlines() if x)
        password = headers.pop('ps')
    
        if __password__ and __password__ != password:
            self.abort(403, '403 Forbidden')
            return
    
        payload = wsgi_input.read() if 'Content-Length' in headers else None
        if 'Content-Encoding' in headers:
            if headers['Content-Encoding'] == 'deflate':
                payload = zlib.decompress(payload, -zlib.MAX_WBITS)
                headers['Content-Length'] = str(len(payload))
                del headers['Content-Encoding']
    
        #开始处理payload.
        self.response.write("ps OK, process data...")
    
    
routes = [
    webapp2.Route(r'/user/<user:.*>', handler=UserHandler, name='user'),
    webapp2.Route(r'/sign', handler=Login, name='sign'),
    webapp2.Route(r'/admin/up', handler=Upload, name='upload')
]

config = {}
config['webapp2_extras.sessions'] = {
    'secret_key': 'dagouMM-very-very-secret',
}

app = webapp2.WSGIApplication(routes=routes, debug=True, config=config)

app.error_handlers[404] = handle_404
app.error_handlers[500] = handle_500

def main():
    app.run()

if __name__ == '__main__':
    main()
